<template>
  <!-- 选择省市区的选择器组件 -->
  <div class="select-district">
    <el-select
      v-model="province"
      value-key="F_id"
      placeholder="省份"
      @change="changeProvince"
    >
      <el-option
        v-for="item in provinceList"
        :key="item.F_id"
        :value="item"
        :label="item.F_name"
      ></el-option>
    </el-select>
    <el-select
      v-model="city"
      value-key="F_id"
      placeholder="市"
      @change="changeCity"
    >
      <el-option
        v-for="item in cityList"
        :key="item.F_id"
        :value="item"
        :label="item.F_name"
      ></el-option>
    </el-select>
    <el-select
      v-model="county"
      value-key="F_id"
      placeholder="区（县）"
      @change="changeCounty"
    >
      <el-option
        v-for="item in countyList"
        :key="item.F_id"
        :value="item"
        :label="item.F_name"
      ></el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  props: {
    areaId: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      provinceList: [],
      cityList: [],
      countyList: [],
      province: {},
      city: {},
      county: {},
    };
  },
  async mounted() {
    this.area_id = this.areaId;
    this.provinceList = await this.getDistricts();
  },
  methods: {
    async changeProvince(val) {
      this.province = val;
      // 地区id为0代表全部不选,即全国
      this.area_id = val.F_id;
      if (val.F_id === 0) this.cityList = [];
      else this.cityList = await this.getDistricts();
      this.$emit("update:areaId", this.area_id);
      this.countyList = [];
      this.city = this.county = {};
    },
    async changeCity(val) {
      this.city = val;
      // 如果选了全部
      if (val.F_id === 0) {
        // 把地区id回退到上一级的id
        this.area_id = this.province.F_id;
        this.countyList = [];
      } else {
        this.area_id = val.F_id;
        this.countyList = await this.getDistricts();
      }
      this.$emit("update:areaId", this.area_id);
      this.county = {};
    },
    changeCounty(val) {
      this.county = val;
      this.area_id =
        val.F_id === 0
          ? this.city.F_id === 0
            ? this.province.F_id
            : this.city.F_id
          : val.F_id;
      this.$emit("update:areaId", this.area_id);
    },
    async getDistricts() {
      const res = await this.$api.getDistricts2({
        F_parent_id: this.area_id,
      });
      const F_districts = res.F_districts || [];
      F_districts.unshift({ F_id: 0, F_name: "全部" });
      return F_districts;
    },
  },
};
</script>

<style lang='less' scoped>
.select-district {
  display: inline-block;
}
</style>
